﻿using Common.Net;
using Common.Security;
using LitJson;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace Common.WeiXin
{
    public class WeiXinHelper
    {

        /// <summary>
        /// 签名验证
        /// </summary>
        /// <returns></returns>
        public static bool VerifySignature()
        {
            string signature = HttpContext.Current.Request["signature"];
            string timestamp = HttpContext.Current.Request["timestamp"];
            string nonce = HttpContext.Current.Request["nonce"];
            if (string.IsNullOrEmpty(signature) || string.IsNullOrEmpty(timestamp) || string.IsNullOrEmpty(nonce)) return false;

            string[] stringArray = { token, timestamp, nonce };
            Array.Sort(stringArray);
            string calculateSignature = Secure.SHA1(string.Join(string.Empty, stringArray));

            //签名验证
            return calculateSignature != null && calculateSignature.ToLower() == signature.ToLower();
        }

        /// <summary>
        /// 微信授权URL
        /// </summary>
        /// <param name="redirectUrl"></param>
        /// <returns></returns>
        public static string GetAuthorize(string redirectUrl)
        {
            return string.Format("https://open.weixin.qq.com/connect/oauth2/authorize?appid={0}&redirect_uri={1}&response_type=code&scope=snsapi_base#wechat_redirect",
                appId,
                UrlEncoder.EncodeUTF8(redirectUrl));
        }

        /// <summary>
        /// 通过授权后的code获取OpenID
        /// </summary>
        /// <returns></returns>
        public static string GetOpenID()
        {
            string code = HttpContext.Current.Request["code"];
            if (string.IsNullOrEmpty(code))
            {
                //未授权
                return string.Empty;
            }

            string url = string.Format("https://api.weixin.qq.com/sns/oauth2/access_token?appid={0}&secret={1}&code={2}&grant_type=authorization_code"
                , ConfigurationManager.AppSettings["WeiXinAppID"], ConfigurationManager.AppSettings["WeiXinAppSecret"], code);
            string result = HttpRequestHelper.getContentUTF8(url);
            JsonData json = JsonMapper.ToObject(result);

            if (json.Keys.Contains("errcode"))
            {
                return string.Empty;
            }

            string openId = json["openid"].ToString();
            if (string.IsNullOrEmpty(openId))
            {
                return string.Empty;
            }

            return openId;
        }

        #region http请求
        /// <summary>
        /// 获取接收到消息的XML字符串
        /// </summary>
        /// <returns></returns>
        public static string GetReceiveXml()
        {
            Stream stream = HttpContext.Current.Request.InputStream;
            var bytes = new byte[stream.Length];
            stream.Read(bytes, 0, (int)stream.Length);
            return Encoding.UTF8.GetString(bytes);
        }
        #endregion

        /// <summary>
        /// 服务号access_token
        /// </summary>
        public static string accessToken
        {
            get
            {
                return WeiXinAccessToken.accessToken;
            }
        }

        #region 微信配置信息
        /// <summary>
        /// 微信appID
        /// </summary>
        public static readonly string appId = ConfigurationManager.AppSettings["WeiXinAppID"];
        /// <summary>
        /// 微信appsecret
        /// </summary>
        public static readonly string appSecret = ConfigurationManager.AppSettings["WeiXinAppSecret"];
        /// <summary>
        /// 微信Token
        /// </summary>
        public static readonly string token = ConfigurationManager.AppSettings["WeiXinToken"];
        /// <summary>
        /// 微信号
        /// </summary>
        public static readonly string weiXinNum = ConfigurationManager.AppSettings["WeiXinNum"];
        #endregion

        #region 微信接口地址
        /// <summary>
        /// 发送模板消息地址
        /// </summary>
        public static string templateMsgUri { get { return string.Format("https://api.weixin.qq.com/cgi-bin/message/template/send?access_token={0}", accessToken); } }
        #endregion

        #region 模版消息

        #endregion
    }
}
